package com.sqin.taskflow.task;

import com.sqin.taskflow.config.TaskFlowConfig;
import com.sqin.taskflow.exception.WorkflowException;
import com.sqin.taskflow.utils.ValidateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableInterceptor.SUCCESSFUL;

import java.util.List;
import java.util.concurrent.*;

@Slf4j
@Data
public class MultiTask extends AbsTask {

    private List<SubMultiTask> taskList;

    private Integer allowCount=0;

    public MultiTask() {
    }

    public MultiTask(List<SubMultiTask> singleTaskList) {
        this.taskList = singleTaskList;
    }

    public MultiTask(List<SubMultiTask> singleTaskList, Integer allowCount) {
        this.taskList = singleTaskList;
        this.allowCount = allowCount;
    }


    @Override
    public void run() {
        TaskFlowConfig.listen.beforeExecute(this);
        this.result = this.execute();
        TaskFlowConfig.listen.afterExecute(this);
    }

    @Override
    public Object execute() {
        ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(
                TaskFlowConfig.corePoolSize,
                TaskFlowConfig.maximumPoolSize,
                TaskFlowConfig.keepAliveTime,
                TaskFlowConfig.unit,
                TaskFlowConfig.workQueue);
        CompletableFuture[] futures = new CompletableFuture[this.taskList.size()];
        for (int i = 0;i<this.taskList.size();i++){
            futures[i] = CompletableFuture.runAsync(
                    this.taskList.get(i), customThreadPool);
        }
        CompletableFuture.allOf(futures).join();
        int successCount = 0;
        for(AbsTask task:this.taskList){
            if (!(task.getResult() instanceof Exception)){
                successCount++;
            }
        }
        if (successCount<this.allowCount){
            throw new WorkflowException("成功数量较少不允许通过");
        }
        return null;
    }

}
